import type { UserInfo } from '@/apis/auth'
import type { UserReq } from '@/apis/system/type'
import { logout } from '@/apis/auth'
import { useAuthStore } from '@/store/auth'
import { goLoginPage } from '@/utils/page'
import { defineStore } from 'pinia'

function storeSetup() {
  const userInfo = ref<Partial<UserInfo>>({})
  const setUserInfo = (val: UserInfo) => {
    userInfo.value = val
  }

  const clearUserInfo = () => {
    userInfo.value = {}
  }

  // 更新用户信息
  const updateUserInfo = (val: UserReq) => {
    userInfo.value = {
      ...userInfo.value,
      ...val,
    }
  }

  // 退出登录
  const handleLogout = async () => {
    const authStore = useAuthStore()
    if (authStore.authInfo.token) {
      await logout()
    }
    // 清空用户信息
    clearUserInfo()
    // 跳转到登录页
    goLoginPage()
  }

  return {
    userInfo,
    setUserInfo,
    clearUserInfo,
    updateUserInfo,
    handleLogout,
  }
}

export const useUserStore = defineStore('user', storeSetup, { persist: true })
